package com.cheer.ba.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.app.oss.UploadPicManager;
import com.cheer.ba.choosepic.ui.AlbumAty;
import com.cheer.ba.choosepic.ui.GalleryAty;
import com.cheer.ba.choosepic.util.Bimp;
import com.cheer.ba.choosepic.util.FileUtils;
import com.cheer.ba.choosepic.util.ImageItem;
import com.cheer.ba.choosepic.util.PublicWay;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.TagModel;
import com.cheer.ba.model.ToJsonModel;
import com.cheer.ba.presenter.impl.CommentPresenter;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.service.LocationService;
import com.cheer.ba.utils.DensityUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.TextViewUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.flowlayout.EvaluateAdapter;
import com.cheer.ba.widget.flowlayout.FlowTagView;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: hq
 * Email: 834138841@qq.com
 * Comment: 图片发布
 * Date: 2017-07-27 17:37
 */
public class ArticlePublishAty extends BaseCommAty implements ShowPopupView.OnItemPopupClick, AdapterView.OnItemClickListener {

    //文字
    @BindView(R.id.id_article_edit)
    EditText mEditText;
    private String mSaveText;
    private String mLength;
    //可输入数量
    @BindView(R.id.id_article_num_txt)
    TextView mTxtNum;

    //标签
    @BindView(R.id.id_choose_sign_linear)
    LinearLayout mLinearSign;
    @BindView(R.id.id_article_tagview)
    FlowTagView mTagList;
    private EvaluateAdapter mTagAdp;

    //girdview
    @BindView(R.id.id_article_gridV)
    GridView myGridView;
    private CommonAdapter<ImageItem> mAdapter;
    private List<ImageItem> mSaveImg = new ArrayList<ImageItem>();

    //位置
    @BindView(R.id.id_article_location)
    TextView mTxtLocation;
    @BindView(R.id.id_article_switchbtn)
    SwitchButton mSwitchBtn;
    //定位服务
    private LocationService mLocationService;

    //添加图片
    public ImageItem mAddImg;

    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"拍照", "从相册中选取"};

    //存储tagId
    private String mSaveTagId;
    //存储地址
    private String mSaveLocation;
    //存储图片地址
    private String picJson;
    private int width;

    //判断是定位权限还是图片权限 true 图片 false 位置
    private boolean recordAuth;

    private OilMealPresenter mOilMealPresenter;

    //1 图片 2 视频
    private int action_type;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //图片上次成功
                case 1:
                    ((CommentPresenter) presenter).publishDynamic(true, mSaveText, mSaveTagId, picJson, "1", mSaveLocation);
                    break;
            }
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_article_publish, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new CommentPresenter();

        mOilMealPresenter = new OilMealPresenter();
        mOilMealPresenter.attachView(this);
        mOilMealPresenter.setmUpLoadPicManager();
    }

    @Override
    public void initView() {
//        action_type = getIntent().getIntExtra(IntentKey.General.KEY_TYPE, Constants.DEFAULTVALUE);
//        if (action_type == 1) {
        setTitleText("图文发布");
        popupView = new ShowPopupView(aty);
        popupView.setOnItemPopupClick(this);
        Bimp.tempSelectBitmap.clear();
        mAddImg = new ImageItem();
        mAddImg.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_unfocused));
        mAddImg.isDel = true;
//        } else {
//            setTitleText("视频发布");
//        }

        //标签
        mTagAdp = new EvaluateAdapter(this);
        mTagList.setAdapter(mTagAdp);
        mTagList.setItemClickListener(new FlowTagView.TagItemClickListener() {
            @Override
            public void itemClick(int position) {
                TagModel e = (TagModel) mTagAdp.getItem(position);
                mSaveTagId = e.uid;
                mTagAdp.setCheckAtPosFalse(position, true);
            }
        });

        //当前位置
        mSwitchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    recordAuth = false;
                    mTxtLocation.setText("正在定位...");
                    checkPermissSdcard();
                } else {
                    mTxtLocation.setText("所在位置");
                    mSaveLocation = "";
                }
            }
        });
        mSwitchBtn.setChecked(true);

        width = DensityUtils.getScreenW(aty) / 4;
        LinearLayout.LayoutParams grid = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, width * 3);
        myGridView.setLayoutParams(grid);
        myGridView.setColumnWidth(width);
        myGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

        setTitleRight("发布", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mSaveText)) {
                    SVProgressHUD.showInfoWithStatus(aty, "至少说点什么吧");
                    return;
                }
                //发布
                if (mSaveImg.isEmpty() || mSaveImg.size() == 1) {
                    //无图片，纯文字
                    ((CommentPresenter) presenter).publishDynamic(true, mSaveText, mSaveTagId, picJson, "1", mSaveLocation);
                } else {
                    //有图片
                    handPicPath();
                }
            }
        });
        EventBus.getDefault().register(this);
        ((CommentPresenter) presenter).getTagList(false, "2");
    }

    public void handPicPath() {
        List<String> mPaths = new ArrayList<String>();
        for (ImageItem item : Bimp.tempSelectBitmap) {
            if (!StringUtils.isEmpty(item.getImagePath())) {
                mPaths.add(item.getImagePath());
            }
        }
        mOilMealPresenter.uploadPic(mPaths, null);
    }

    @Override
    public void initData() {
        TextViewUtils.setSpannableStyleColor("150/150", 0, 3, mTxtNum, R.color.color_main);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveText = s + "";
                int l = 0;
                if (StringUtils.isEmpty(mSaveText)) {
                    l = 150;
                    mLength = "";
                } else {
                    int m = mSaveText.length();
                    if (m <= 150) {
                        l = 150 - m;
                        mLength = mSaveText;
                    } else {
                        l = 0;
                        mEditText.setText(mLength);
                        mEditText.setSelection(mLength.length());
                    }
                }
                TextViewUtils.setSpannableStyleColor(l + "/150", 0, (l + "").length(), mTxtNum, R.color.color_main);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mAdapter = new CommonAdapter<ImageItem>(aty, mSaveImg, R.layout.item_published_grida) {
            @Override
            public void convert(ViewHolder helper, ImageItem item) {
                if (null != item) {
                    int position = helper.getPosition();
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width - DensityUtils.px2dip(mContext, 5), width - DensityUtils.px2dip(mContext, 5));
                    ImageView mImg = helper.getView(R.id.item_grida_image);
                    mImg.setLayoutParams(params);
                    if (position == PublicWay.total_num) {
                        mImg.setVisibility(View.GONE);
                    } else {
                        mImg.setImageBitmap(item.getBitmap());
                    }
                }
            }
        };
        myGridView.setAdapter(mAdapter);
        myGridView.setOnItemClickListener(this);
        handList();
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.PUBLISH_DYNAMIC)) {
                //发布成功
                SVProgressHUD.showSuccessWithStatus(aty, "发布成功");
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.PUBLISH_DYNAMIC;
                EventBus.getDefault().post(event);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else if (TextUtils.equals(tag, ConstantTag.GET_TAGS_SUCCESS)) {
                //获得标签列表
                List<TagModel> tags = (List<TagModel>) t;
                if (null != tags && !tags.isEmpty()) {
                    mLinearSign.setVisibility(View.VISIBLE);
                    mTagAdp.setItems(tags);
                }
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_SUCCESS)) {
                //图片上传成功
                List<UploadPicManager.UploadInfo> resultList = (List<UploadPicManager.UploadInfo>) t;
                handPicToJson(resultList);
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_FAIL)) {
                //图片上传失败
                SVProgressHUD.showInfoWithStatus(aty, "发布失败，请检查网络");
            }
        }
    }

    /**
     * 处理上传成功的界面
     */
    private void handPicToJson(List<UploadPicManager.UploadInfo> resultList) {
        List<ToJsonModel> toJsons = new ArrayList<ToJsonModel>();
        for (UploadPicManager.UploadInfo info : resultList) {
            ToJsonModel model = new ToJsonModel();
            model.fileName = "";
            model.serialName = "";
            model.fileType = 1;
            model.fileExt = StringUtils.getPicNameFromPath(info.fileSavePath);
            model.fileSize = 0;
            model.fileUrl = info.fileSavePath;
            model.smallPrefix = "";
            model.mediumPrefix = "";
            model.md5 = "";
            toJsons.add(model);
        }
        picJson = new Gson().toJson(toJsons);
        LogUtils.LogD("图片上传成功----", picJson);
        Message msg = new Message();
        msg.what = 1;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ImageItem mItem = mSaveImg.get(position);
        if (mItem.isDel) {
            recordAuth = true;
            checkPermissCamer();
        } else {
            Intent intent = new Intent(aty, GalleryAty.class);
            intent.putExtra(IntentKey.General.KEY_POS, position);
            intent.putExtra(IntentKey.General.KEY_BOOLEAN, true);
            startActivity(intent);
        }
    }

    /**
     * 处理列表数据
     */
    public void handList() {
        mSaveImg.clear();
        if (!Bimp.tempSelectBitmap.isEmpty()) {
            mSaveImg.addAll(Bimp.tempSelectBitmap);
        }
        mSaveImg.add(mAddImg);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            if (recordAuth) {
                toPhotoGraph();
            } else {
                getLocation();
            }
        }
    }

    /**
     * 下载图片
     */
    private void toPhotoGraph() {
        popupView.showAtLocPop(mRootViewLL, POPUP_ITEMS);
    }

    private static final int TAKE_PICTURE = 0x000001;

    //记录拍照 0 拍照 1 相册
    private int mRecordIndex;
    //0 拍照 1 定位
    private int mRecordIsLocation;

    @Override
    public void OnItemClick(int position, String tag) {
        switch (position) {
            case 0:
                mRecordIsLocation = 0;
                mRecordIndex = 0;
                checkPermissSdcard();
                break;
            case 1:
                mRecordIsLocation = 0;
                mRecordIndex = 1;
                checkPermissSdcard();
                //从照片选择
                Intent intent = new Intent(aty, AlbumAty.class);
                showActivity(aty, intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    String path = FileUtils.saveBitmap(bm, fileName);

                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    takePhoto.setImagePath(path);
                    Bimp.tempSelectBitmap.add(takePhoto);
                    handList();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.General.KEY_FINISH)) {
            handList();
        }
    }

    /**
     * 检测用户定位权限
     */
    private void checkPermissSdcard() {
        String[] perms;
        if (mRecordIsLocation == 0) {
            perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        } else {
            perms = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        }
        if (!mayRequestPermission(perms)) {
            return;
        }
        if (mRecordIsLocation == 0){
            takePhoto();
        }else{
            getLocation();
        }
    }

    public void takePhoto(){
        if (mRecordIndex == 0){
            //拍照
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(openCameraIntent, TAKE_PICTURE);
        }
    }

    /**
     * 获取定位地址
     */
    public void getLocation() {
        mLocationService = ((App) getApplication()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(mListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        //定位
        mLocationService.start();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                Address mAddress = location.getAddress();
                mSaveLocation = mAddress.city + mAddress.district + mAddress.street;
                if (mSaveLocation.contains("null")) {
                    mSaveLocation = "";
                    mTxtLocation.setText("定位失败");
                } else {
                    mTxtLocation.setText(mSaveLocation);
//                    mSaveLocatio
// n = location.getProvince() + "|" + location.getCity() + "|" + location.getDistrict() + "|" + location.getAddress();
                }
            }
            mLocationService.stop();
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };

    @Override
    protected void onStop() {
        //注销监听
        if (null != mLocationService) {
            mLocationService.unregisterListener(mListener);
            //停止定位服务
            mLocationService.stop();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
